package com.yanyeori.framework.datasource.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.yanyeori.framework.datasource.mybatisplus.mapper.BaseMapper;
import com.yanyeori.framework.datasource.mybatisplus.service.IService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * mybatis-plus增强ServiceImpl
 *
 * @author chenkuan 2023/8/28
 */
public class ServiceImpl<M extends BaseMapper<T>, T> extends com.baomidou.mybatisplus.extension.service.impl.ServiceImpl<M, T> implements IService<T> {
    /**
     * sql批量插入
     *
     * @param entityList 实体对象集合
     * @param batchSize  批次提交数量
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertBatch(List<T> entityList, int batchSize) {
        Assert.isFalse(batchSize < 1, "batchSize must not be less than one");
        if (CollectionUtils.isEmpty(entityList)) return false;
        int size = entityList.size(), update = 0, fromIndex = 0, toIndex = Math.min(batchSize, size);
        while (fromIndex < size) {
            update += baseMapper.insertBatchSomeColumn(entityList.subList(fromIndex, toIndex));
            fromIndex = toIndex;
            toIndex = Math.min(toIndex + batchSize, size);
        }
        return update == size;
    }
}
